<template>
  <div class="flex h-full">
    <div class="flex flex-col flex-1 overflow-hidden">
      <SearchContainer search-text="搜索" @search="getData()" @reset="onReset">
        <div class="flex justify-between">
          <a-form ref="formRef" class="form-style-flex" :model="searchData" :label-col="{ style: { width: '80px' } }">
            <a-form-item v-if="!isDefault" name="pyjm" class="w-[300px] mr-2">
              <a-input v-model:value="searchData.pyjm" placeholder="项目名称/助记码" />
            </a-form-item>
            <a-form-item label="" name="dateRange" class="w-52 mr-2">
              <SelectArea use-cache set-cache @change="onChangeArea" />
            </a-form-item>
            <a-form-item label="申请时间" name="dateRange" class="w-80 mr-4">
              <a-range-picker v-model:value="searchData['dateRange']" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :allow-clear="false" @change="getData()" />
            </a-form-item>
          </a-form>
          <a-form class="flex">
            <SelectDrugRoom
              v-model:value="drugStoreId"
              placeholder="选择药房"
              is-department="1"
              :params="{ isProducer: '1', storetype: '3' }"
              class="w-64 mb-2 mr-4"
              @select="onSelectDrugRoom"
            />
            <a-form-item class="w-64" label="审核人">
              <a-select v-model:value="reviewer" :options="pharmacistSelectData" placeholder="请选择" @change="setLocalStorageEvent" />
            </a-form-item>
          </a-form>
        </div>
      </SearchContainer>
      <a-card class="w-full flex-1 mt-2">
        <a-button type="primary" class="mb-2" :disabled="defaultCheckedKeys.length <= 0" @click="onDispensing"> 批量发放 </a-button>

        <template v-if="isDefault">
          <BaseTable :loading="loading" column-code="000551" :row-selection="rowSelection" :data-source="tableData" row-key="bh" fill :pagination="pagination">
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'mc'">
                <PopoverTable
                  :config="detailConfig"
                  :params="{
                    stdate: searchData?.dateRange[0],
                    eddate: searchData?.dateRange[1],
                    pageNum: 1,
                    pageSize: 999,
                    wardId: searchData.wardId,
                    ypbh: record.bh
                  }"
                  :width="700"
                >
                  <template #bodyCell="{ column: popColumn, record: popRecord, index: popIndex }">
                    <template v-if="popColumn.dataIndex === 'xh'">
                      <span>{{ popIndex + 1 }}</span>
                    </template>
                    <template v-if="popColumn.dataIndex === 'brName'">
                      <span>{{ popRecord.brName }}</span>
                      <span class="ml-4">{{ popRecord.brXb }}</span>
                      <span class="ml-4">{{ popRecord.brAge }}</span>
                    </template>
                  </template>
                  <div class="w-full h-full flex justify-between items-center">
                    <div class="flex items-baseline truncate">
                      <div :title="record.mc" class="text-primary">{{ record.mc }}</div>
                      <div v-if="record.gg" :title="record.gg" class="ml-2 text-xs">{{ record.gg }}</div>
                      <div v-if="record.cj" :title="record.cj" class="ml-2 text-xs max-w-[64px] truncate">{{ record.cj }}</div>
                    </div>
                  </div>
                </PopoverTable>
              </template>
              <template v-if="column.dataIndex === 'sl'"> {{ record.sl }}{{ record.dw }} </template>
            </template>
          </BaseTable>
        </template>

        <template v-else>
          <BaseTable :loading="loading" column-code="000876" :row-selection="rowSelection" :data-source="tableData" row-key="key" fill :pagination="false">
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'xh'">
                <span>{{ index + 1 }}</span>
              </template>
              <template v-if="column.dataIndex === 'brName'">
                <span>{{ record.brName }}</span>
                <span class="ml-4">{{ record.brXb }}</span>
                <span class="ml-4">{{ record.brAge }}</span>
              </template>
              <template v-if="column.dataIndex === 'mc'">
                <div class="flex items-center truncate">
                  <div :title="record.mc">{{ record.mc }}</div>
                  <div v-if="record.gg" :title="record.gg" class="ml-2 text-xs">{{ record.gg }}</div>
                  <div v-if="record.cj" :title="record.cj" class="ml-2 text-xs max-w-[64px] truncate">{{ record.cj }}</div>
                </div>
              </template>
            </template>
          </BaseTable>
        </template>
      </a-card>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { post } from '@/utils/request'
import useUserStore from '@/store/user'
import { isHave } from '@/utils/tools'

const { empId } = useUserStore()
const drugStoreId = ref(undefined) //发药药房
const formRef = ref(null)
const isDefault = ref(false)
const pharmacistSelectData = ref([])
const defaultCheckedKeys = ref([])
const reviewer = ref(undefined) //审核人
const searchData = ref({
  dateRange: [dayjs().format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')],
  pyjm: '',
  wardId: ''
})

const rowSelection = ref({
  checkStrictly: true,
  selectedRowKeys: defaultCheckedKeys,
  onChange: (selectedRowKeys) => {
    defaultCheckedKeys.value = selectedRowKeys
  }
})
//获取
const { loading, tableData, getData, pagination } = useTable({
  url: getSystemConfig('MTR_DISPENSE_PAGE_MODE') === '1' ? '/inp/zyyf/getInpMtrDistributionSuppliesYp' : '/inp/zyyf/getInpMtrDistributionSupplies',
  immediate: false,
  formatParams: () => {
    return {
      stdate: searchData.value?.dateRange[0],
      eddate: searchData.value?.dateRange[1],
      pyjm: searchData.value.pyjm,
      wardId: searchData.value.wardId
    }
  },
  formatResult: (result) => {
    // 如果是汇总自己加标志key
    result.forEach((item, index) => {
      item.key = index
    })
    return result
  }
})
const detailConfig = ref({
  url: '/inp/zyyf/getInpMtrDistributionSupplies',
  columnCode: '000558',
  rowKey: 'xh',
  formatResult: (data) => {
    return data.map((item, index) => ({
      ...item,
      xh: index + 1
    }))
  }
})

//获取审核人下拉（类别为药剂师）
const getSelectPharmacist = async () => {
  const { code, data } = await post('/operation/opex/getEmpInfoList', {
    emplbid: '5',
    yxzt: 0,
    pageNum: 1,
    pageSize: 9999,
    notEmpIdList: [empId] // 当前登录但id
  })
  if (code !== 0) return
  pharmacistSelectData.value = data.map((item) => {
    return {
      label: item.empName,
      value: item.empId
    }
  })
  const reviewerValue = JSON.parse(window.localStorage.getItem('grantReviewer'))
  if (reviewerValue && reviewerValue.time && reviewerValue.value) {
    //保存24小时
    if (dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') >= 0 && dayjs(dayjs().format()).diff(reviewerValue.time, 'hour') < 24) {
      if (isHave(pharmacistSelectData.value, reviewerValue.value)) reviewer.value = reviewerValue.value
    }
  }
}
const onDispensing = async () => {
  if (defaultCheckedKeys.value.length <= 0) {
    message.error('请至少选择一项')
    return
  }
  if (!drugStoreId.value) return message.error('请选择药房')
  if (!reviewer.value) return message.error('请选择审核人')
  const ids = getSelectedIds()
  // return
  const res = await post('/inp/zyyf/doSaveInpMtrDistributionSupplies', ids)
  if (res.code !== 0) return message.error(res.msg || '操作失败')
  message.success('发放成功')
  getData()
  onReset()
}
const getSelectedIds = () => {
  const resultArr = []
  const selectObj = {
    bh: '',
    sl: '',
    yzId: [],
    shr: '',
    ckbh: '',
    wardId: '',
    stdate: '',
    eddate: ''
  }
  let selectData = []
  defaultCheckedKeys.value.forEach((item) => {
    if (isDefault.value) {
      selectData = tableData.value.filter((it) => {
        return it.bh === item
      })
    } else {
      // 如果是汇总自己加的一个唯一标识key
      selectData = tableData.value.filter((it) => {
        return it.key === item
      })
    }

    if (selectData && selectData.length > 0) {
      selectObj.bh = selectData[0].bh
      selectObj.sl = selectData[0].sl
      selectObj.yzId = selectData[0].yzId
      selectObj.shr = reviewer.value
      selectObj.ckbh = drugStoreId.value
      selectObj.wardId = searchData.value.wardId
      selectObj.stdate = searchData.value?.dateRange[0]
      selectObj.eddate = searchData.value?.dateRange[1]
      resultArr.push(selectObj)
    }
  })
  return resultArr
}
const onChangeArea = (val) => {
  searchData.value.wardId = val
  getData()
}
const onSelectDrugRoom = (val) => {
  drugStoreId.value = val.id
  // window.localStorage.setItem(
  //   'dispensingMaterialDrugStoreId',
  //   JSON.stringify({
  //     value: drugStoreId.value
  //   })
  // )
}
const onReset = () => {
  formRef.value.resetFields()
  tableData.value = []
  defaultCheckedKeys.value = []
}
const setLocalStorageEvent = () => {
  window.localStorage.setItem(
    'grantReviewer',
    JSON.stringify({
      time: dayjs().format(),
      value: reviewer.value
    })
  )
}

onMounted(async () => {
  getSelectPharmacist()
  isDefault.value = getSystemConfig('MTR_DISPENSE_PAGE_MODE') === '1' // 0：通用模式|1：明细模式(默认使用) 【物资发放】【门诊发放】页面、【住院发放】页面样式
  // const drugStoreIdValue = JSON.parse(window.localStorage.getItem('dispensingMaterialDrugStoreId'))
  // drugStoreId.value = await judgeDrugStoreStatus(drugStoreIdValue?.value, '1', '3')
})
</script>

<style lang="less" scoped>
:deep(.ant-table-row-expand-icon) {
  display: none;
}
</style>
